import axios from "axios";
import { errorDeal, getStore, successDeal } from "@/utils/utils";
import NProgress from 'nprogress'

axios.interceptors.request.use(
  function (config) {
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  function (response) {
    return response;
  },
  function (error) {
    return Promise.reject(error);
  }
);
/**
 *@describe http请求
 *@method {String} 请求方式
 *@url {String} 接口地址
 *@params {Object} 对应接口参数
 **/

export default async function _http(method = "post", { url, apiName = "" }, params = {}, loading = true, headers = {}) {
  if (loading) {
    NProgress.start();
  }

  //----获取token,Authorization 鉴权信息
  const token = window.localStorage.getItem("USER_TOKEN_INRE") || '';
  const uesrInfo = getStore("USER_INFO_INRE") || {};
  const Authorization = getStore("USER_AUTHOR_INRE") || {
    Authorization: `'','','',3,20,''`,
  };

  let json = {}
  // if (url == '/ums/w/company/login') {
  //   json = {
  //     username: uesrInfo.username || '',
  //   }
  // }
  json = {
    token: token ? `Bearer ${token}` : '',
    username: uesrInfo.username || '',
  }

  // if (PROCESS_ENV.ENVIRONMENT == 'Production') {
  //   url = '/coupon_h5' + url
  // }

  return axios({
    method: method,
    url: '' + url,

    headers: Object.assign(
      {
        "Content-Type": "application/json;charset=UTF-8;",
        "platformHeadType": "rcmsPlatform",
      },
      json,
      Authorization || {},
      headers
    ),
    params: method === "get" ? params : "" || method === "delete" ? params : "",
    data: typeof params === "object" ? JSON.stringify(params) : params,
    timeout: 1000 * 60 * 2,
    responseType: params.responseType == "blob" ? "blob" : undefined,
    withCredentials: true,
  }).then((res) => {
    if (loading) {
      NProgress.done()
    }
    // 数据流，直接返回
    if (params.responseType == "blob") {
      return res;
    }

    if (res && res.data && (res.data.code == 200 || res.data.result == 200 || res.data.result == 0 || res.data.enterCode == 200 || res.data.error == 200)) {
      return res.data;
    } else throw res.data;
  }).catch((error) => {
    if (loading) {
      NProgress.done()
    }
    errorDeal(error, url);
    throw error;
  });
}
